import Vue from 'vue'
import axios from "axios"
// import router from "@/router"
import { Toast } from 'vant'
Vue.use(Toast)
// 默认值
axios.defaults.withCredentials = true
axios.defaults.baseURL = "api/"

const tokenStr = localStorage.getItem('token')
// 响应拦截器
axios.interceptors.response.use(
  (response)=> {
    // console.log('response',response)
    // 未登录
    if (response.data.error_code == 422) {
      Toast({
          message: response.data.error,
          type: 'error'
      });
      // alert(response.data.error)
      // router.push({ name: "login" })
      return Promise.reject(response.data)
      // 其他错误
    } else if (response.data.error_code) {
      //   Message({
      //     message: response.data.error,
      //     type: "warning"
      //   })
      alert(response.data.error)
      return Promise.reject(response.data)
      // 成功
    } else {
      return response.data
    }
  },
  (error)=> {
    Toast({
      message: '验证码过期或已超时',
      type: 'error'
  });
    return Promise.reject(error)
  }
)


//请求拦截器
axios.interceptors.request.use(
  config => {
    //在所有请求头部添加token值
    const token = JSON.parse(tokenStr)
    if (token) {

      config.headers.Authorization = `${token.token_type} ${token.access_token}`

    }
    config.headers.Accept = 'application/json'
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// get 请求
function get(opt) {
  // const token=JSON.parse(tokenStr)
  // console.log('token',token)
  // console.log('opt',opt)
  return axios.get(opt.url, { params: opt.data })
}

// post 请求
function post(opt) {
  return axios.post(opt.url, opt.data, {})
}

// 上传
function upload(opt) {
  return axios.post(opt.url, opt.data, {
    headers: { "Content-Type": "multipart/form-data" },
    onUploadProgress: opt.onUploadProgress
  })
}

export { get, post, upload }
